package ro.gateway.aida.charts;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.jfree.chart.servlet.ChartDeleter;
import org.jfree.chart.servlet.ServletUtilities;

/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: Jun 19, 2004
 * Time: 2:25:35 PM
 * To change this template use File | Settings | File Templates.
 */
public class ChartProviderServlet extends HttpServlet {
	protected void doGet(HttpServletRequest request,
					 HttpServletResponse response)
		  throws ServletException, IOException {
		HttpSession session = request.getSession();
		String filename = request.getParameter("c");

		if (filename == null) {
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
			return;
		}

		//  Replace ".." with ""
		//  This is to prevent access to the rest of the file system
		filename = ServletUtilities.searchReplace(filename, "..", "");

		//  Check the file exists
		File file = new File(System.getProperty("java.io.tmpdir"), filename);
		if (!file.exists()) {
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
			return;
		}

		//  Check that the graph being served was created by the current user
		//  or that it begins with "public"
		boolean isChartInUserList = false;
		ChartDeleter chartDeleter = (ChartDeleter) session.getAttribute("JFreeChart_Deleter");
		if (chartDeleter != null) {
			isChartInUserList = chartDeleter.isChartAvailable(filename);
		}

		boolean isChartPublic = false;
		if (filename.length() >= 6) {
			if (filename.substring(0, 6).equals("public")) {
				isChartPublic = true;
			}
		}

		if (isChartInUserList || isChartPublic) {
			//  Serve it up
			ServletUtilities.sendTempFile(file, response);
		} else {
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
			return;
		}
		return;
	}
}
